<?php
namespace app\index\controller\base;
use app\index\controller\BaseIndex;
use szktor\ClinicDict; //诊所门店公共字典
use app\common\model\ClinicDictsheet; //字典表数据
use app\common\model\ClinicConfig;
/*
* 前台-基础设置 -> 参数设置
* index/base.config/index
*/
class Config extends BaseIndex
{
    protected $noNeedLogin = [];  //无需登录的方法，同时也就不需要鉴权了
    protected $noNeedRight = ['save']; //无需鉴权的方法，但需要登录

    //初始化
    public function initialize()
    {
        parent::initialize();
    }

    //首页
    public function index()
    {
        if($this->request->isPost() || $this->request->isAjax())
        {
            try
            {
                $data = $this->request->only(['dicttype'],'post');
                $data['dicttype'] = isset($data['dicttype']) ? strtolower($data['dicttype']) : '';
                if(!$data['dicttype'])
                {
                    return ['err' => '1', 'msg' => '参数错误，无法获取数据'];
                }
                $arr = ClinicConfig::getBaseConfigArray($data['dicttype'],$this->admin['clinic_id']);
                return ['err' => '0', 'msg' => '获取成功', 'list' => $arr];
            }catch (\think\Exception $e){ // use think\Exception;
                return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
            }
        }
        $this->assign([
            'sz_cate_list' => ClinicDict::getClinicConfigCateList(), //参数设置分类列表
        ]);
        return $this->view->fetch();
    }
    //保存
    public function save()
    {
        if(!$this->request->isAjax())
        {
            return json(['err' => '1', 'msg' => '对不起，您的访问方式有误']);
        }
        try
        {
            $post = $this->request->only(['list','dicttype'],'post');
            $post['dicttype'] = isset($post['dicttype']) ? strtolower($post['dicttype']) : '';
            if(!$post['dicttype'])
            {
                return ['err' => '2', 'msg' => '参数错误，无法更新数据'];
            }
            $post['list'] = isset($post['list']) ? $post['list'] : false;
            if(!$post['list'] || !is_array($post['list']))
            {
              return json(['err' => '3', 'msg' => '当前页面配置参数无需保存']);
            }
            $data = $post['list'];
            foreach($data as $k => $v)
            {
                $map = [
                    ['group','=',$post['dicttype']],
                    ['name','=',trim($k)]
                ];
                $r = ClinicDictsheet::getSplitDb($this->admin['clinic_id'],'clinic_config')
                    ->where($map)->update(['value' => trim($v)]);
            }
            $res = __clearnSystemCache();
            $msg = '配置参数更新成功';
            if (!$res) $msg .= '，请手动清理缓存';
            return json(['err' => '0', 'msg' => $msg]);
        }catch (\think\Exception $e){ // use think\Exception;
           return json(['err' => '500', 'msg' => '错误：' . $e->getMessage()]);
        }
    }
}
